package com.yz.jdd.module.cashier.result;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiniu.android.utils.StringUtils;
import com.trello.rxlifecycle.ActivityEvent;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.module.cashier.scanpay.ScanpayActivity;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.webview.Router;

import rx.functions.Action1;

/**
 * Created by shibin on 2016/12/29.
 * 收款/退款/储值--成功结果页
 */

public class PaySuccessActivity extends BaseActivity implements View.OnClickListener {
    private String orderId = "";
    private String str_voice_type;
    private String orderType;
    private String payType;
    private Context context = PaySuccessActivity.this;
    private Request_Pay request_pay;
    private String totalAmountStr;
    private String receiptAmountStr;
    private String discountAmountStr;//优惠金额
    private String molingAmountStr;
    private String gooodsAmount;
    private TextView resultAmount;
    private TextView tvValue1;
    private TextView tvRight;
    private TextView title;
    private TextView status;
    private TextView resultAmountType;

    private TextView detailKey1;
    private TextView detailKey2;
    private TextView detailKey3;
    private TextView detailKey4;
    private TextView detailKey5;
    private TextView detailKeyPaytype;
    private TextView detailValue1;
    private TextView detailValue2;
    private TextView detailValue3;
    private TextView detailValue4;
    private TextView detailValuePaytype;
    private ImageView successImg;
    private LinearLayout detailLayout4;
    private LinearLayout detailLayout3;
    private TextView message;
    private Button pay_btn_complete;
    private Button btn_detail;//查看订单
    private int delatedTime = 0;

    private String from;
    private String refundMsg;
    String verifyCode;

    //营销新增
    private String receiveAmountFromPayGate;//收银实收
    private String deductionAmount;//津贴
    private TextView detailValue_syss;
    private TextView detailValue_gljss;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_success);

        initData();
        initView();
    }

    private Handler mHandler = new Handler();
    private Runnable runnableDelated = new Runnable() {
        @Override
        public void run() {
            delatedTime--;
            pay_btn_complete.setText("完成（" + delatedTime + "S）");
            if (delatedTime == 0) {
                payComplete("");
            } else {
                mHandler.postDelayed(this, 1000);
            }
        }
    };


    /**
     * 点餐订单需调用订单详情接口获取必要参数
     */
    void initData() {
        request_pay = (Request_Pay) getIntent().getSerializableExtra(PayConfig.INTENT_ORDER_FROM);
        verifyCode = getIntent().getStringExtra("verifyCode");
        if (request_pay != null) {
            orderId = Tools.getSafeString(request_pay.getOrderId());
            orderType = Tools.getSafeString(request_pay.getOrderType());
            payType = Tools.getSafeString(request_pay.getPayType());
            totalAmountStr = Tools.getSafeString(request_pay.getTotalAmount(), "0.00");
            receiptAmountStr = Tools.getSafeString(request_pay.getReceiptAmount(), "0.00");
            discountAmountStr = Tools.getSafeString(request_pay.getDiscountAmount(), "0.00");
            molingAmountStr = Tools.getSafeString(request_pay.getMoling(), "0.00");
            gooodsAmount = Tools.getSafeString(request_pay.getGooodsAmount(), "0.00");

            //营销新增
            receiveAmountFromPayGate = Tools.getSafeString(request_pay.getReceiveAmountFromPayGate(), "0.00");
            ;//收银实收
            deductionAmount = Tools.getSafeString(request_pay.getDeductionAmount(), "0.00");//津贴

            from = request_pay.getFrom();
            if ("refund".equals(from)) {//退款信息
                refundMsg = getIntent().getStringExtra("refundMsg");
            }
            if (PayConfig.TYPE_ORDER_DISH.equals(request_pay.getOrderType()) && !"refund".equals(from)) {
//                getDishOrderDetail();
            }
        }

        //RxBus -- 支付成功之后，关闭栈内此页面
        RxBus.with(this).

                setEvent(Events.PAY_COMPETE_TO_CLOSE).

                setEndEvent(ActivityEvent.DESTROY).

                onNext(new Action1<Events<?>>() {
                    @Override
                    public void call(Events<?> events) {
                        if (Events.PAY_COMPETE_TO_CLOSE.equals(events.getContent())) {
                            finish();
                        }
                    }
                }).create();
    }

    @Override
    protected void onStop() {
        mHandler.removeCallbacks(runnableDelated);
        super.onStop();
    }


    void initView() {
        pay_btn_complete = (Button) findViewById(R.id.pay_btn_complete);
        resultAmount = (TextView) findViewById(R.id.payresult_amount);
        resultAmountType = (TextView) findViewById(R.id.payresult_amount_type);
        tvValue1 = (TextView) findViewById(R.id.detail_value1);
        tvRight = (TextView) findViewById(R.id.right_nav);
        tvRight.setVisibility(View.VISIBLE);
        title = (TextView) findViewById(R.id.title_nav);
        status = (TextView) findViewById(R.id.payresult_status);
        message = (TextView) findViewById(R.id.payresult_message);
        detailKey1 = (TextView) findViewById(R.id.detail_key1);
        detailKey2 = (TextView) findViewById(R.id.detail_key2);
        detailKey3 = (TextView) findViewById(R.id.detail_key3);
        detailKey4 = (TextView) findViewById(R.id.detail_key4);
        detailKey5 = (TextView) findViewById(R.id.detail_key5);
        detailKeyPaytype = (TextView) findViewById(R.id.detailkey_paytype);

        detailValue1 = (TextView) findViewById(R.id.detail_value1);
        detailValue2 = (TextView) findViewById(R.id.detail_value2);
        detailValue3 = (TextView) findViewById(R.id.detail_value3);
        detailValue4 = (TextView) findViewById(R.id.detail_value4);
        detailLayout4 = (LinearLayout) findViewById(R.id.detail_layout4);
        detailLayout3 = (LinearLayout) findViewById(R.id.detail_layout3);
        detailValuePaytype = (TextView) findViewById(R.id.detailvalue_paytype);
        successImg = (ImageView) findViewById(R.id.pay_result_icon);


        detailValue_syss = (TextView) findViewById(R.id.detail_value_syss);
        detailValue_gljss = (TextView) findViewById(R.id.detail_value_gljss);

        btn_detail = findViewById(R.id.btn_detail);
        btn_detail.setOnClickListener(this);
        resultAmount.setText(receiptAmountStr);
        tvValue1.setText("¥" + totalAmountStr);
        // 区分交易，储值
        if ("refund".equals(from)) {//退款信息
            LogUtils.d("  ----------- 退款");
            title.setText("退款结果");
            if (StringUtils.isNullOrEmpty(refundMsg)) {
                status.setText("退款受理成功");
            } else {
                status.setText(refundMsg);
            }
            resultAmountType.setText("申请退款金额");
            detailKeyPaytype.setText(getString(R.string.txt_refund_type));
            resultAmount.setText(Tools.getSafeString(request_pay.getRefundMoney(), "0.00"));

            detailKey1.setText("申请退款金额");
            detailValue1.setText("¥" + request_pay.getRefundMoney());
            findViewById(R.id.detail_layout3).setVisibility(View.GONE);
            findViewById(R.id.detail_layout2).setVisibility(View.GONE);
            findViewById(R.id.detail_layout4).setVisibility(View.GONE);
            detailLayout4.setVisibility(View.GONE);

            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(context) != null) {
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("退款受理成功");
                SpeechUtilOffline.getInstance(context).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }

        } else {
            if (PayConfig.TYPE_ORDER_DEAL.equals(orderType) || PayConfig.TYPE_ORDER_DISH.equals(orderType)) {
                //支付信息
                delatedTime = PreferencesUtils.getInt(PaySuccessActivity.this, BaseConfigs.PREF_SUCCESSS_HINT_TIME, 0);
                if (delatedTime != 0) {
                    pay_btn_complete.setText("完成（" + delatedTime + "S）");
                    mHandler.postDelayed(runnableDelated, 1000);
                }
                LogUtils.d(" ----------- 支付");
                title.setText("支付结果");
                status.setText("收款成功");
                resultAmountType.setText("实收金额");
                resultAmountType.setVisibility(View.GONE);
                //支付显示字段：应收金额、实收金额、优惠金额、收款方式
                detailKey1.setText("订单金额");
                detailKey2.setText("实收金额");
                detailKey3.setText("优惠金额");
                detailKeyPaytype.setText("收款方式");
                detailValue1.setText("¥" + totalAmountStr);
                detailValue2.setText("¥" + receiptAmountStr);
                detailValue3.setText("¥" + discountAmountStr);

                findViewById(R.id.detail_layout2).setVisibility(View.GONE);

                //收银实收/津贴实收为0或为null，则不展示该行数据，其他情况展示
                //收银实收
                if (!TextUtils.isEmpty(receiveAmountFromPayGate) && Double.parseDouble(receiveAmountFromPayGate) > 0) {
                    findViewById(R.id.detail_layout_syss).setVisibility(View.VISIBLE);
                    detailValue_syss.setText("¥" + receiveAmountFromPayGate);
                } else {
                    findViewById(R.id.detail_layout_syss).setVisibility(View.GONE);
                }
                //津贴
                if (!TextUtils.isEmpty(deductionAmount) && Double.parseDouble(deductionAmount) > 0) {
                    findViewById(R.id.detail_layout_gljss).setVisibility(View.VISIBLE);
                    detailValue_gljss.setText("¥" + deductionAmount);
                } else {
                    findViewById(R.id.detail_layout_gljss).setVisibility(View.GONE);
                }


                if (!"0".equals(Tools.decimalZeroRoundness(discountAmountStr))) {
                    detailLayout3.setVisibility(View.VISIBLE);
                }
                //需要判断,支付宝支付

                if (PayConfig.TYPE_PAY_ALIPAY.equals(payType) && !"0".equals(Tools.decimalZeroRoundness(gooodsAmount))) {
                    detailLayout4.setVisibility(View.VISIBLE);
                    detailKey4.setText("商品核销金额");
                    detailValue4.setText("¥" + gooodsAmount);
                }
                if (!"0".equals(Tools.decimalZeroRoundness(molingAmountStr))) {
                    detailLayout4.setVisibility(View.VISIBLE);
                    detailKey4.setText("抹零金额");
                    detailValue4.setText("¥" + molingAmountStr);
                }


            } else {
                if (PayConfig.TYPE_ORDER_RECHARGE.equals(orderType)) {//储值信息
                    LogUtils.d("  ----------- 储值");
                    title.setText("储值结果");
                    status.setText("储值成功");
                    resultAmountType.setText("储值金额");
                    //储值显示字段：储值金额、赠送金额、会员卡号、收款方式
                    detailKey1.setText("实收金额");
                    detailKey2.setText("赠送金额");
                    detailKey3.setText("会员卡号");
                    detailKeyPaytype.setText("储值方式");
                    detailValue2.setText("¥" + discountAmountStr);
                    resultAmount.setText(totalAmountStr);
                    detailValue1.setText("¥" + receiptAmountStr);
                } else {
                    LogUtils.d("  ----------- 撤销");
                    tvRight.setVisibility(View.GONE);
                    status.setText("撤销成功");
                    message.setVisibility(View.VISIBLE);
                    message.setText(getString(R.string.txt_cancelorder_success_message));
                    title.setText("收款结果");
                    resultAmountType.setText("实收金额");
                    //撤销订单显示字段：应收金额，支付方式
                    detailKeyPaytype.setText("支付方式");
                    resultAmount.setText("0.00");
                    findViewById(R.id.detail_layout1).setVisibility(View.GONE);
                    findViewById(R.id.detail_layout2).setVisibility(View.GONE);
                    findViewById(R.id.detail_layout3).setVisibility(View.GONE);
                    findViewById(R.id.detail_layout4).setVisibility(View.GONE);
                }
            }
        }

        //支付方式

        if (PayConfig.TYPE_PAY_CASH.equals(payType)) {
            str_voice_type = "现金";
        } else {
            if (PayConfig.TYPE_PAY_ALIPAY.equals(payType)) {
                str_voice_type = "支付宝";
                successImg.setBackgroundResource(R.mipmap.casher_success);
            } else {
                if (PayConfig.TYPE_PAY_MEMBERCARD.equals(payType)) {
                    str_voice_type = "会员卡";
                } else {
                    if (PayConfig.TYPE_PAY_UNION.equals(payType)) {
                        str_voice_type = "银联";
                    } else {
                        if (PayConfig.TYPE_PAY_WEIXIN.equals(payType)) {
                            str_voice_type = "微信";
                            successImg.setBackgroundResource(R.mipmap.casher_success_green);
                        } else {
                            if (PayConfig.TYPE_PAY_YUNSHANFU.equals(payType)) {
                                str_voice_type = "云闪付";
                                successImg.setBackgroundResource(R.mipmap.casher_success_green);
                            } else {
                                if (PayConfig.TYPE_PAY_MINISTOREVALUE.equals(payType)) {
                                    str_voice_type = "余额支付";
                                    successImg.setBackgroundResource(R.mipmap.casher_success_green);
                                } else {
                                    successImg.setBackgroundResource(R.mipmap.casher_success_green);
                                }
                            }
                        }
                    }
                }
            }
        }
        detailValuePaytype.setText(str_voice_type);
        //语音播报支付方式+收款成功+xx.xx元
        if ("商品核销".equals(verifyCode)) {
            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(context) != null) {
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("口碑商品券核销成功");
                SpeechUtilOffline.getInstance(context).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }
        } else {
            try {
                if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(getApplicationContext()) != null && !PayConfig.TYPE_ORDER_CANCEL.equals(orderType) && !"refund".equals(from)) {
                    String playVoice;
                    if ("1".equals(totalAmountStr)) {
                        playVoice = str_voice_type + "收款成功一园";
                    } else {
                        if ("0.1".equals(totalAmountStr)) {
                            playVoice = str_voice_type + "收款成功0.1元";
                        } else {
                            playVoice = str_voice_type + "收款成功" + totalAmountStr + "园";
                        }
                    }
                    LogUtils.e("=== PaySuccessActivity play: " + playVoice);
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent(playVoice);
                    if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_LOCAL_RECEIVABLES, true)) {
                        SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //查看订单详情
        tvRight.setText("完成");
        tvRight.setOnClickListener(this);

        findViewById(R.id.pay_btn_complete).setOnClickListener(this);
        findViewById(R.id.back_nav).setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pay_btn_complete) {
            payComplete("");
        }
        if (v.getId() == R.id.back_nav) {
            payComplete("");
        }
        if (v.getId() == R.id.right_nav) {
            payComplete("main");
        }

        if (v.getId() == R.id.btn_detail) {
            mHandler.removeCallbacks(runnableDelated);
            Router.startOrderDetail(PaySuccessActivity.this, orderId, orderType,
                    request_pay.getShopId(), "0", "1", "");
        }
    }

    //完成
    private void payComplete(String isMain) {
        boolean pos_fixed = PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_POS_FIXED_AMOUNT, false);
        if (!"refund".equals(from)) {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            if (!PayConfig.TYPE_ORDER_DISH.equals(request_pay.getOrderType())) {
                if (pos_fixed) {
                    intentFixedScanpay();
                } else {
                    if (TextUtils.isEmpty(isMain)) {
                        startActivity(new Intent(PaySuccessActivity.this, CashierActivity.class));
                    }
                }
            }
            finish();
        } else {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            if (PayConfig.TYPE_ORDER_DEAL.equals(orderType) || PayConfig.TYPE_ORDER_RECHARGE.equals(orderType)) {
                boolean flag = PreferencesUtils.getBoolean(this, BaseConfigs.CASHIER_REFUND, false);
                if (flag) {
                    if (pos_fixed) {
                        intentFixedScanpay();
                    } else {
                        startActivity(new Intent(PaySuccessActivity.this, CashierActivity.class));
                    }
                }
            }
            finish();
        }
    }

    //跳转固定金额扫码收款
    private void intentFixedScanpay() {
        Request_Pay request_pay = new Request_Pay();
        request_pay.setOrderType(PayConfig.TYPE_ORDER_DEAL);
        request_pay.setTotalAmount(PreferencesUtils.getString(this, BaseConfigs.POS_FIXED_AMOUNT_VALUE, ""));
        request_pay.setFrom(PayConfig.INIENT_FIXED_SCAN);
        Intent intent = new Intent(this, ScanpayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            payComplete("");
            return true;
        }
        return false;
    }

}
